package com.lody.virtual.client.stub;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import com.lody.virtual.server.notification.NotificationCompat;


/**
 * @author Lody
 *
 */
public class DaemonService extends Service {

	private static final int NOTIFY_ID = 1001;

	public static void startup(Context context) {
		context.startService(new Intent(context, DaemonService.class));
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		startup(this);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			startForegroundService(new Intent(this, InnerService.class));
			NotificationChannel channel = new NotificationChannel(""+NOTIFY_ID, "notification_name", NotificationManager.IMPORTANCE_LOW);
			NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManager.createNotificationChannel(channel);
			Notification.Builder builder = new Notification.Builder(this);
			builder.setChannelId(""+NOTIFY_ID);
			startForeground(NOTIFY_ID, builder.build());
		}else {
			startService(new Intent(this, InnerService.class));
			startForeground(NOTIFY_ID, new Notification());
		}

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}

	public static final class InnerService extends Service {

		@Override
		public int onStartCommand(Intent intent, int flags, int startId) {
			NotificationChannel channel = null;
			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
				channel = new NotificationChannel(""+NOTIFY_ID, "notification_name", NotificationManager.IMPORTANCE_LOW);
				NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				notificationManager.createNotificationChannel(channel);
				Notification.Builder builder = new Notification.Builder(this);
				builder.setChannelId(""+NOTIFY_ID);
				startForeground(NOTIFY_ID, builder.build());
				stopForeground(true);
				stopSelf();
			}else {
				startForeground(NOTIFY_ID, new Notification());
				stopForeground(true);
			}
			return super.onStartCommand(intent, flags, startId);
		}

		@Override
		public IBinder onBind(Intent intent) {
			return null;
		}
	}


}
